package org.hybridlabs.source.beautifier;

import java.lang.reflect.Method;

public class CompatibilityHelper {

    /**
     * Resolves compatibility issue concerning org.openarchitectureware.xpand2.output.FileHandle changes.
     *
     * @param info
     * @param charSequence
     * @return
     */
    public static CharSequence getBuffer(org.openarchitectureware.xpand2.output.FileHandle info) {
        try {
            Method getterMethod = info.getClass().getMethod("getBuffer", null);
            return (CharSequence) getterMethod.invoke(info, null);
        } catch (Exception e) {
            throw new RuntimeException("Incompatibilty with oAW classes. Method getBuffer cannot be invoked.",
                e);
        }
    }

    /**
     * Resolves compatibility issue concerning org.openarchitectureware.xpand2.output.FileHandle changes.
     *
     * @param info
     * @param sequence
     */
    public static void setBuffer(org.openarchitectureware.xpand2.output.FileHandle info, CharacterSequence sequence) {
        try {
            try {

                // from version 4.2.0 on
                Method method =
                    info.getClass()
                        .getMethod("setBuffer",
                        new Class[] { CharSequence.class });
                method.invoke(info, new Object[] { sequence });
                return;
            } catch (NoSuchMethodException e) {

                // method does not exist
            }

            try {

                // until version 4.1.x
                Method method =
                    info.getClass()
                        .getMethod("setBuffer",
                        new Class[] { StringBuffer.class });
                method.invoke(info, new Object[] { sequence.getStringBuffer() });
                return;
            } catch (NoSuchMethodException e) {

                // method does not exist
            }
        } catch (Exception e) {
            throw new RuntimeException("Incompatibilty with oAW classes. Method setBuffer with expected parameters not found.",
                e);
        }
        throw new RuntimeException(
            "Incompatibilty with oAW classes. Method setBuffer with expected parameters not found.");
    }
}
